'use strict';
var http = require('http');
var https = require('https');
var fs = require('fs');
var express = require('express');
var serveIndex = require('serve-index');
var socketIO = require('socket.io')(http,https);

//日志
var log4js = require('log4js');

log4js.configure({
    appenders: {
        file: {
            type: 'file',
            filename: 'app.log',
            layout: {
                type: 'pattern',
                pattern: '%r %p - %m',
            }
        }
    },
    categories: {
        default: {
            appenders: ['file'],
            level: 'debug'
        }
    }
});
//日志
var logger = log4js.getLogger();

//创建http server
var app = express();
app.use(serveIndex('./public'));
app.use(express.static('./public'));
var http_server = http.createServer(app);

//socketIO 信令服务绑定HTTP及HTTPS服务，先绑定在开启端口

//处理连接，类似java SocketServer的accept
socketIO.on('connection', (socket) => {
    //用户加入情况
    socket.on('join', (room) => {
        socket.join(room);
        var myRoom = io.sockets.adapter.rooms[room];
        var users = Object.keys(myRoom.sockets).length;
        logger.log('the number of user in room is:' + users);
        //socket.emit('joined', room, socket.id);//给本类回信息
        //socket.to(room).emit('joined', room, socket.idp);//除自己外的房间所有人
        //socket.in(room).emit('joined', room, socket.idp);//给房间所有人信息
        socket.broadcast.emit('joined', room, socket.id);//除自己全部发
    });
    //用户离开情况
    socket.on('leave', (room) => {
        socket.join(room);
        var myRoom = io.sockets.adapter.rooms[room];
        var users = Object.keys(myRoom.sockets).length;
        logger.log('the number of user in room is:' + (users-1));

        //socket.emit('joined', room, socket.id);//给本类回信息
        //socket.to(room).emit('joined', room, socket.idp);//除自己外的房间所有人
        //socket.in(room).emit('joined', room, socket.idp);//给房间所有人信息
        socket.broadcast.emit('joined', room, socket.id);//除自己全部发
    })
})


http_server.listen(8888, '0.0.0.0');


//创建https server ，需要申请HTTPS认证
// var options = {
//   key:fs.readFileSync('./cet/证书位置'),
//   cert:fs.readFileSync('./cert/证书位置')
// }
//var https_server = https.createServer(options,app);
//http_server.listen(443,'0.0.0.0');







